package com.example.myapplication;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myapplication.socket.ChatService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class SocketActivity extends AppCompatActivity {
    private ChatService chatService;
    private Button btSengMessage;
    private TextView tvMessage;
    private EditText etSendMessage;
    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_socket);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        EventBus.getDefault().register(this);
        btSengMessage = findViewById(R.id.btSendMessage);
        tvMessage = findViewById(R.id.tvMessage);
        etSendMessage=findViewById(R.id.etSentMessage);
        chatService=new ChatService();
        btSengMessage.setOnClickListener((view)->{
            String message=etSendMessage.getText().toString();
            chatService.sendMessage(message);
            etSendMessage.setText("");
        });

        new Thread(() -> {
            while (true) {
                final String message = chatService.receiveMessage();
                if (message != null) {
                    EventBus.getDefault().post(new MessageEvent<>(message + "\n"));
                }
            }

        }).start();

    }
    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent<String> event) {
        String data = event.getData();
        tvMessage.append(data);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        chatService.stop();
    }
}